package com.wiz.weixin.manager;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.wiz.weixin.common.TencentConstant;
import com.wiz.weixin.service.StationService;
import com.wiz.weixin.util.TencentUtil;
import com.wiz.weixin.util.WxMessageUtil;

/**
 * 腾讯相关逻辑器
 * @author Hakeny
 */
@Service("tencentManager")
public class TencentManager implements TencentConstant {
	private transient final Logger log = LoggerFactory.getLogger(getClass());

	private final String web_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token";

	@Resource
	private HttpManager httpManager;
	@Resource
	private MenuManager menuManager;
	@Resource
	private StationService stationService;


	/**
	 * 通过微信要求获取用户网页授权的方式获取用户的openId
	 * @return
	 * @throws Exception
	 */
	public String getOpenId(String code){
		try{
			// 调用接口
			List<NameValuePair> formparams = new ArrayList<NameValuePair>();  
		    formparams.add(new BasicNameValuePair("appid", WX_APP_ID));
		    formparams.add(new BasicNameValuePair("secret", WX_APP_SECRET));
		    formparams.add(new BasicNameValuePair("code", code));
		    formparams.add(new BasicNameValuePair("grant_type", "authorization_code"));
			String response = httpManager.getResponseByHttpPost(web_token_url,formparams);
			
			if(StringUtils.isBlank(response)){
				log.error("getOpenId(null) from tencent fail,code="+code);
				return null;
			}
			JSONObject json = new JSONObject(response);
			if (!json.isNull("openid")) {
				return json.getString("openid");
			}else{
				log.error("getOpenId(not openId) from tencent fail,json="+json);
				return null;
			}
		}catch(Exception e){
			e.printStackTrace();
			log.error("getOpenId from tencent fail,code="+code,e);
		}
		return null;
	}

	/**
	 * 根绝配置文件建立微信menu
	 * 
	 * @throws JSONException
	 */
	public String createMenu() throws JSONException {
		if (menuManager.getMenu() != 0) {
			return "fail";
		}
		return "success";
	}

	/**
	 * 处理微信发来的请求
	 *
	 * @param request
	 * @return
	 */
	public String processRequest(HttpServletRequest request) {
		String respMessage = "success";
		try {
			// 默认返回的文本消息内容
			String respContent = "success";
			// xml 请求解析
			Map<String, String> requestMap = WxMessageUtil.parseXml(request);
			// 发送方帐号（open_id）
			String fromUserName = requestMap.get("FromUserName");
			// 公众帐号
			String toUserName = requestMap.get("ToUserName");
			// 消息类型，需要根据此消息判断是何种消息
			String msgType = requestMap.get("MsgType");
			if (msgType.equals(WxMessageUtil.REQ_MESSAGE_TYPE_TEXT)) {// 只响应文本消息
				 String content = requestMap.get("Content");
				 if(content.toLowerCase().startsWith("bind")){
					 boolean b = stationService.bindBossWeixin(fromUserName,content);
					 if(b){
						 respContent = "绑定成功";
					 }else{
						 respContent = "绑定失败";
					 }
					 log.info("openId="+fromUserName+" bind "+respContent);
					 respMessage = WxMessageUtil.textMessageToXml(fromUserName, toUserName, respContent);
				 }
			} else if (msgType.equals(WxMessageUtil.REQ_MESSAGE_TYPE_EVENT)) {// 事件推送
				// 事件类型
				String eventType = requestMap.get("Event");
				String eventKey = requestMap.get("EventKey");
				// 订阅
				if (eventType.equals(WxMessageUtil.EVENT_TYPE_SUBSCRIBE)) {
					if (eventKey != null && !eventKey.equals("")) {
						String stationId = eventKey.split("_")[1];
						int vcode = (int) (Math.random() * 999999);
						StringBuffer buffer = new StringBuffer();
						buffer.append("【");
						buffer.append("】欢迎您").append("\n");
						respContent = buffer.toString();
					} else {
						respContent = "欢迎关注油掌柜管理者！！！";
					}
					respMessage = WxMessageUtil.textMessageToXml(fromUserName, toUserName, respContent);
				} else if (eventType.equals(WxMessageUtil.EVENT_TYPE_SCAN)) {// 扫描
					// Constant.map.put("", fromUserName);
					int vcode = (int) (Math.random() * 999999);
					StringBuffer buffer = new StringBuffer();
					buffer.append("【");
					buffer.append("】欢迎您").append("\n");
					
					respContent = buffer.toString();
					respMessage = WxMessageUtil.textMessageToXml(fromUserName, toUserName, respContent);
				} else if (eventType.equals(WxMessageUtil.EVENT_TYPE_CLICK)) {//click事件
					
				} else if (eventType.equals("LOCATION")) {
					
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage());
		}
//		return respMessage;
		try {
			return new String(respMessage.getBytes("utf-8"),"ISO8859_1");
		} catch (UnsupportedEncodingException e) {
			
		}
		return "success";
	}

	/**
	 * 长链接转成短链接 提高扫码速度和成功率
	 * @param accessToken
	 * @param URL
	 * @return
	 */
	public String shortURL(String URL){
		String shortURL = null;
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/shorturl?access_token=ACCESS_TOKEN";
		requestUrl = requestUrl.replace("ACCESS_TOKEN", WxAccessManager.getTencent_wx_token());
		String jsonMsg = "{\"action\":\"long2short\",\"long_url\":\"%s\"}";
		String response = TencentUtil.httpsRequest(requestUrl, "POST", String.format(jsonMsg, URL));
		try {
			org.json.JSONObject jsonObject = new org.json.JSONObject(response);
			String code = jsonObject.getString("errcode");
			if (code.equals("0")) {
				shortURL = jsonObject.getString("short_url");
			} else {
				String errorMsg = jsonObject.getString("errmsg");
				log.error(errorMsg);
			}
		} catch (JSONException e) {
//			e.printStackTrace();
		}
		return shortURL;
	}

}
